package com.slanmao.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.slanmao.common.entity.AccessToken;
import com.slanmao.common.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <CODE>AuthController</CODE>
 * 微信授权接口
 * @author fenrir
 * @Date 19-2-26
 */
@RestController
@Slf4j
@RequestMapping("/wx")
public class AuthController {

    private static final String APPID = "wxe7d249b30b01bf45";

    private static final String APPSECRET = "3087a74df54fc3e2972e50be6b4670f6";

    @Autowired
    private HttpUtils httpUtils;


    /**
     * 生成用于获取access_token的Code的Url
     * @param redirectUrl
     * @return
     */
    public String getRequestCodeUrl(String redirectUrl) {
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                APPID, redirectUrl, "snsapi_userinfo", "xxxx_state");
    }



//    /**
//     * 获取用户信息
//     *
//     * @param accessToken
//     * @param openId
//     * @return
//     */
//    public Map<String, String> getUserInfo(String accessToken, String openId) {
//        Map<String, String> data = new HashMap();
//        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
//        log.info("request user info from url: {}", url);
//        JsonObject userInfo = null;
//        try {
//            String response = HttpUtils.get(url);
//            Gson token = new Gson();
//            userInfo = token.fromJson(response, JsonObject.class);
//            log.info("get userinfo success. [result={}]", userInfo);
//            data.put("openid", userInfo.get("openid").toString().replaceAll("\"", ""));
//            data.put("nickname", userInfo.get("nickname").toString().replaceAll("\"", ""));
//            data.put("city", userInfo.get("city").toString().replaceAll("\"", ""));
//            data.put("province", userInfo.get("province").toString().replaceAll("\"", ""));
//            data.put("country", userInfo.get("country").toString().replaceAll("\"", ""));
//            data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", ""));
//        } catch (Exception ex) {
//            log.error("fail to request wechat user info. [error={}]", ex);
//        }
//        return data;
//    }


    /**
     * 获取请求用户信息的access_token
     *
     * @param code
     * @return
     */
    public AccessToken getUserInfoAccessToken(String code) {
        try {
            String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    APPID, APPSECRET, code);
            log.info("request accessToken from url: {}", url);
            String response = httpUtils.get(url);
            log.info("请求token返回:"+response);
            Gson token = new Gson();
            return token.fromJson(response, AccessToken.class);
        } catch (Exception ex) {
            log.error("fail to request wechat access token", ex);
        }
        return null;
    }


    /**
     * 路由控制
     *
     * @param request
     * @param code
     * @return
     */
    @GetMapping("/auth")
    public @ResponseBody String auth(HttpServletRequest request,
                                     @RequestParam("code") String code) {
        String requestURI = request.getRequestURI();
        log.info("请求地址:"+requestURI);
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info("请求参数:"+new Gson().toJson(parameterMap));
        //通过这个code获取access_token
        AccessToken token = getUserInfoAccessToken(code);
        log.info("获取到的access");
        String openId = token.getOpenid();
        if (StringUtils.isNotEmpty(openId)) {
            log.info("try getting user info. [openid={}]", openId);
            //使用access_token获取用户信息
            log.info("received user info. [result={}]", token);
            return openId;
        }
        return "openid为空";
    }

    @GetMapping("/test")
    public @ResponseBody String test(@RequestParam("openid")String openid,@RequestParam("id")String id){
        return "工单号:"+id+"\r\n"+"openid:"+openid;
    }
}
